#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json
import math
import time
import urllib.parse
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class JilinJlsrmzf6d01Policy(BaseTaxPolicySpider):
    name = 'jilin_jlsrmzf_6d01_policy'
    
    province = '吉林省'
    city = ''
    county = ''
    park = ''
    source = '吉林省人民政府'
    url = 'https://xxgk.jl.gov.cn/?stit=%E5%90%89%E6%94%BF%E5%8F%91&num=4'
    
    def start_requests(self):
        for url in [
            self.url,
            'https://xxgk.jl.gov.cn/?stit=%E5%90%89%E6%94%BF%E5%87%BD&num=4',
            'https://xxgk.jl.gov.cn/?stit=%E5%90%89%E6%94%BF%E6%98%8E%E7%94%B5&num=4',
            'https://xxgk.jl.gov.cn/?stit=%E5%90%89%E6%94%BF%E5%8A%9E%E5%8F%91&num=4',
            'https://xxgk.jl.gov.cn/?stit=%E5%90%89%E6%94%BF%E5%8A%9E%E5%87%BD&num=4',
            'https://xxgk.jl.gov.cn/?stit=%E5%90%89%E6%94%BF%E5%8A%9E%E6%98%8E%E7%94%B5&num=4',
        ]:
            yield scrapy.Request(url, callback=self.parse_content)

    def parse_content(self, response, **kwargs):
        # prev_item = response.meta.get('item')
        url = 'https://infogate.jl.gov.cn/govsearch/jsonp/zf_jd_list.jsp?'
        channelId = response.xpath('.').re_first(r'var channelId = "(.*)";')
        lb = response.xpath('.').re_first(r'var lb = "(.*)";')
        stit = response.url.split('stit=')[1].split('&')[0]
        stit = urllib.parse.unquote(stit)
        params = {
            "page": "1",
            "lb": lb,
            "callback": "result",
            "sword": stit,
            "searchColumn": "wenhao",
            "channelId": channelId,
            "_": f"{int(time.time() * 1000)}"
        }
        temp_url = url + urllib.parse.urlencode(params)
        yield scrapy.Request(temp_url, callback=self.parse_list, meta={"params": params, "url": url})

    def parse_list(self, response, **kwargs):
        params = response.meta.get('params')
        prev_item = response.meta.get('item')
        try:
            json_data = json.loads(response.text.strip()[7:-2])
        except:
            print(params)
        for elem in json_data['data']:
            item = Item()
            item['source_url'] = elem['puburl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['tip']['dates']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total = json_data['num']
            params = response.meta.get('params')
            url = response.meta.get('url')
            total_page = math.ceil(int(total) / 15)
            for page_num in range(2, total_page + 1):
                params['page'] = page_num
                params['_'] = f"{int(time.time() * 1000)}"
                temp_url = url + urllib.parse.urlencode(params)
                yield scrapy.FormRequest(temp_url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False, "params": params, "url": url})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jilin_jlsrmzf_6d01_policy".split())
